var JSON_TEMPLATE_DIR='/static/jsontemplate/';
var XSLT="";
var activityindicator='<img src="/static/images/active.png" alt=" "/>';
var globalpackageid=0;
var globaltoolid=0;
var tool_editted=false;

var higlighted={backgroundColor:"#F6AE37", color:"white"};
var defaultlook={backgroundColor:"#EEEEEE", color:"black"};

$(document).ready(function() {
  // get the list of the users packages
  list_packages();
  // load the xslt for tool rendering
  $.get("/static/style.xslt", function(data){
     XSLT=data;
  });
  $('#maincontent').dialog({modal:true,  title:'QTI Authoring System', width:'1010', height:'700' }); 
});

 

function list_packages() {
  $.post('/list_packages/', {'posted':JSON.stringify({'blank':'blank'})}, function(data) {render_package_list(data)}, "json");
}

function render_package_list(data) {
  $("#list_packages").html($('#list_packagesTemplate').tmpl(data));
  $(".highlightpackage" + globalpackageid).css(higlighted);
}
 
function create_package() {
  
  var inobj=JSON.stringify($("#create_package_form").serializeJSON());
  $("#package_name").val('');
  $("#package_desc").val('');
  $("#create_package_form").dialog('destroy');
  $.post('/create_package/', {'posted':inobj},  function(data){
    render_package_list(data);}
  , "json");
  return false;
}

function create_tool(id) {
  var inobj=JSON.stringify($("#create_tool_form").serializeJSON());
  $('#tool_name').val('');
  $.post('/create_tool/', {'posted':inobj},  function(data){
    render_package(data);}, "json");
  
  $("#create_tool_form").dialog('destroy');
  return false;
}


function render_package(data) {
  $("#show_package").show();
  $("#show_package").html($('#show_packageTemplate').tmpl(data));
  Vanadium.scan_dom();
  $(".highlightpackage" + globalpackageid).css(higlighted);
  $(".highlighttool" + globaltoolid).css(higlighted);
}


function show_package(id) {
  if (tool_editted) {
    if (confirm("Changes to the tool being editted will be lost. Continue?")==false) {
      return false;
    }
  }
  tool_editted=false;
  $(".highlightpackage" + globalpackageid).css(defaultlook);
  globalpackageid=id;
  $.post('/show_package/', {'posted':JSON.stringify({'id':id})}, function(data) {
    render_package(data);
  }, "json");
  
  return false;
}

function delete_tool(id) {
  if (confirm("Are you sure you want to delete this assessment tool?")) {
    if (id==globaltoolid) {
      if (cancel_tool()==false) {
        return false;
      }
    }
    
    $.post('/delete_tool/', {'posted':JSON.stringify({'id':id})}, function(data) {
      render_package(data);
    }, "json");
    return true;
  }
  return false;
}

function show_tool(id) {
  if (id!=globaltoolid) {
    if (cancel_tool()==false) {
      return;
    }
    $("#show_tool").show();
    $(".highlighttool" + globaltoolid).css(defaultlook);
    globaltoolid=id;
    $.post('/show_tool/', {'posted':JSON.stringify({'id':id})}, function(data) {
        $("#show_tool").html($('#show_toolTemplate').tmpl(data));
        //$("#show_tool").dialog({modal:true, title:'Edit Tool - ' + data.name, width:700, height:540});
        $("#contentviewer").transform({error: function(html,xsl,xml,obj,ex) {alert(ex.message);}, xmlstr:data.contents , xslstr:XSLT});
        $("#toolcontentstext").val(data.contents);
        $(".highlighttool" + globaltoolid).css(higlighted);
    }, "json");
    /*}*/
  }
}

function delete_package(id) {
  
  if (confirm("Are you sure you want to delete this assessment package?")) { 
    if (globalpackageid==id) {
      $("#show_package").html('');
      globalpackageid=0;
    } 
    $.post('/delete_package/', {'posted':JSON.stringify({'id':id})}, function(data) {
      render_package_list(data);
    }, "json");
  }
  return false;
}


function append_interaction(strXML) {
  var parser = new DOMImplementation();
  tool_editted=true;
  try {
    //alert($("#toolcontentstext").val());
    //alert('44');
    var domDoc=parser.loadXML($("#toolcontentstext").val());
    //alert('46');
    var docRoot=domDoc.getDocumentElement();
    //alert('48');
    var itemBody=docRoot.getFirstChild();
    //alert('50');
    var newnode=domDoc.importNode(parser.loadXML("<?xml version=\"1.0\"?><content>" + strXML + "</content>").getDocumentElement().getFirstChild(),true);
    //alert('52');
    itemBody.appendChild(newnode);
  } catch(e) {
    alert(e.code);
  }
  //alert("newdoc=" + docRoot.getXML().replace(' xmlns="http://www.w3.org/2000/xmlns/"', ''));
  return docRoot.getXML().replace(' xmlns="http://www.w3.org/2000/xmlns/"', '').replace(' >','>');
   //xmlns="http://www.w3.org/2000/xmlns/"
}

function interactionselected() {
  $("#interactionsparent").children().hide();
  $("#" + $("#interactiontype :selected").val() + "Form").show();
  Vanadium.scan_dom();
}


/*
var formdata=new Object();
var choices= new Array();
*/
var strHTMLSnippit="";
var choicecounter=0;
function processchoiceInteractionForm() {
  try {
    strHTMLSnippit='<choiceInteraction maxChoices="1" responseIdentifier="' + new Date().getTime() + '" shuffle="false">';
    $("#choiceInteractionForm input").each(function(index) {
      if ($(this).attr("name")=="prompt" && $(this).val()!="") {
        strHTMLSnippit=strHTMLSnippit + '<prompt>' + $(this).val() + '</prompt>';
        $(this).val('');
      }
      if ($(this).attr("name")=="choice" && $(this).val()!="") {
        strHTMLSnippit=strHTMLSnippit + '<simpleChoice identifier="'  + new Date().getTime() + '_' + choicecounter + '">' + $(this).val() + '</simpleChoice>';
        choicecounter++
        $(this).val('');
      }
    });
    strHTMLSnippit=strHTMLSnippit + '</choiceInteraction>'; 
    //alert(strHTMLSnippit);
    //alert('starting append');
    var strXML=append_interaction(strHTMLSnippit);
    //alert('append survived');
    strHTMLSnippit='';
    $("#contentviewer").html("");
    $("#contentviewer").transform({error: function(html,xsl,xml,obj,ex) {alert(ex.message);}, xmlstr:strXML , xslstr:XSLT});
    $("#toolcontentstext").val(strXML);
    choicecounter=0;
    return false;
  } catch(e) {
    alert(e.description);
    return false;
  }
}


function processtextEntryInteractionForm() {
  strHTMLSnippit='<extendedTextInteraction expectedLength="1000" responseIdentifier="' + new Date().getTime() + '">';
  
  $("#textEntryInteractionForm input").each(function(index) {
    if ($(this).attr("name")=="prompt") {
      strHTMLSnippit=strHTMLSnippit + '<prompt>' + $(this).val() + '</prompt>';
      $(this).val('');
    }
  });
  strHTMLSnippit=strHTMLSnippit + '</extendedTextInteraction>';
  var strXML=append_interaction(strHTMLSnippit);
  strHTMLSnippit='';
  $("#contentviewer").html("");
  $("#contentviewer").transform({error: function(html,xsl,xml,obj,ex) {alert(ex.message);}, xmlstr:strXML , xslstr:XSLT});
  $("#toolcontentstext").val(strXML);
  return false;
}

function processuploadInteractionForm() {
  strHTMLSnippit='<uploadInteraction responseIdentifier="' + new Date().getTime() + '">';
  
  $("#uploadInteractionForm input").each(function(index) {
    if ($(this).attr("name")=="prompt") {
      strHTMLSnippit=strHTMLSnippit + '<prompt>' + $(this).val() + '</prompt>';
      $(this).val('');
    }
  });
  strHTMLSnippit=strHTMLSnippit + '</uploadInteraction>';
  var strXML=append_interaction(strHTMLSnippit);
  strHTMLSnippit='';
  $("#contentviewer").html("");
  $("#contentviewer").transform({error: function(html,xsl,xml,obj,ex) {alert(ex.message);}, xmlstr:strXML , xslstr:XSLT});
  $("#toolcontentstext").val(strXML);
  return false;
}

function processInstructionsForm() {
  if ($('#thingy').val()!='') {
    strHTMLSnippit=strHTMLSnippit + '<p>' + $('#thingy').val() + '</p>';
    var strXML=append_interaction(strHTMLSnippit);
    strHTMLSnippit='';
    $("#contentviewer").html("");
    $("#contentviewer").transform({error: function(html,xsl,xml,obj,ex) {alert(ex.message);}, xmlstr:strXML , xslstr:XSLT});
    $("#toolcontentstext").val(strXML);
  }
  return false;
}


function addamultiplechoice() {
  $("#choiceoptions").append('<input name="choice" type="text" value=""/><br/>');
}

function save_tool() {
  $("#show_tool").dialog('destroy')
  $.post('/save_tool/', {'posted':JSON.stringify($("#show_tool_form").serializeJSON())}, function(data) {
    show_package(globalpackageid);
  }, "json");
  tool_editted=false;
}

function cancel_tool() {
  if (tool_editted) {
    if (confirm("All Edits to this tool will be lost. Continue?")){
      $("#show_tool").html('');
      $("#show_tool").hide();
      tool_editted=false;
      $(".highlighttool" + globaltoolid).css(defaultlook);
      globaltoolid=0;
      return true;
    } else {
      return false;
    }
  } else {
    $("#show_tool").html('');
    $(".highlighttool" + globaltoolid).css(defaultlook);
    globaltoolid=0;
    $("#show_tool").hide();
    tool_editted=false;
    return true;
  }
}

function delete_interaction(xmlid) {
  if (confirm("This interaction will be deleted. Continue?")){
    var parser = new DOMImplementation();
    tool_editted=true;
    try {
      var domDoc=parser.loadXML($("#toolcontentstext").val());
      var docRoot=domDoc.getDocumentElement();
      var itemBody=docRoot.getFirstChild();
      var domNodeList = itemBody.getChildNodes();
      var nodetodelete=new Object();
      for (i=0; i< domNodeList.length; i++) {
        if (domNodeList.item(i).getAttributes().getNamedItem("responseIdentifier").getNodeValue()==xmlid) {
          nodetodelete=domNodeList.item(i);
        }
      }
      var deletednode=itemBody.removeChild(nodetodelete);
      strXML=docRoot.getXML().replace(' xmlns="http://www.w3.org/2000/xmlns/"', '').replace(' >','>');
      $("#contentviewer").html("");
      $("#contentviewer").transform({error: function(html,xsl,xml,obj,ex) {alert(ex.message);}, xmlstr:strXML , xslstr:XSLT});
      $("#toolcontentstext").val(strXML);
    } catch(e) {
      alert(e.code);
    }
  }
}

function move_interaction_down(xmlid) {
  if ($("#" + xmlid).next().attr('id')) {
   swap_interaction_elements( $("#" + xmlid).next().attr('id'), xmlid);
  }
}

function move_interaction_up(xmlid) {
  if ($("#" + xmlid).prev().attr('id')) {
    swap_interaction_elements(xmlid, $("#" + xmlid).prev().attr('id'));
  }
}



function swap_interaction_elements(firstid, secondid) {
  var parser = new DOMImplementation();
  tool_editted=true;
  try {
    var domDoc=parser.loadXML($("#toolcontentstext").val());
    var docRoot=domDoc.getDocumentElement();
    var itemBody=docRoot.getFirstChild();
    var domNodeList = itemBody.getChildNodes();
    var firstnode=new Object();
    var secondnode=new Object();
    for (i=0; i< domNodeList.length; i++) {
      if (domNodeList.item(i).getAttributes().getNamedItem("responseIdentifier").getNodeValue()==firstid) {
        firstnode=domNodeList.item(i);
      }
      if (domNodeList.item(i).getAttributes().getNamedItem("responseIdentifier").getNodeValue()==secondid) {
        secondnode=domNodeList.item(i);
      }
      //alert(domNodeList.item(i).getNodeName());
      
    }
    itemBody.insertBefore(itemBody.removeChild(firstnode),secondnode );
    var strXML=docRoot.getXML().replace(' xmlns="http://www.w3.org/2000/xmlns/"', '').replace(' >','>');
    $("#contentviewer").html("");
    $("#contentviewer").transform({error: function(html,xsl,xml,obj,ex) {alert(ex.message);}, xmlstr:strXML , xslstr:XSLT});
    $("#toolcontentstext").val(strXML);
  } catch(e) {
    alert(e.code);
  }
    

}

// other peoples stuff

(function( $ ){
  $.fn.serializeJSON=function() {
  var json = {};
  jQuery.map($(this).serializeArray(), function(n, i){
    json[n['name']] = n['value'];
  });
  return json;
  };
})( jQuery );


